#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDate>
#include <QMessageBox>
#include <QList>
#include <QTranslator>
#include <QKeyEvent>
#include <QFile>
#include <QFileDialog>
#include <QTextDocument>
#include <QPrintDialog>
#include <QPrinter>
#include <QPrintPreviewDialog>
#include <QWebView>
#include <QDesktopWidget>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->ui->toolBar->hide();
    this->fpath="";
    this->ui->tw_central->setCurrentIndex(TAB_HEAD);
    this->setWindowTitle(WINDOW_TITLE);

    // инициализируем  XML DOCUMENT
    //this->xmlDoc = new QDomDocument("new");
    this->initXml();

    // Инициализируем конфиг
    this->cfg = new QSettings(QSettings::IniFormat,QSettings::UserScope,"Tori Sakura","t-13");

    // Читаем настройки из конфига
    this->readSettings();

    configPath=QApplication::applicationDirPath()+"/t-13.cfg";
    for(int i = 0 ; i < QApplication::arguments().size(); i++){
        QString arg = QApplication::arguments().at(i);
        if(arg == "-c" or arg == "--config"){
            if(QApplication::arguments().count()>i){
                configPath = QApplication::arguments().at(i+1);
            }
        }else{

            if(arg.mid(0,9)=="--config="){
                configPath= arg.split("=").at(1);
            }
        }
    }
    qDebug()<<"conf "<<configPath;

    this->ui->de_doc->setDate(QDate::currentDate());
    QDate a;
    a.setYMD(QDate::currentDate().year(),QDate::currentDate().month(),1);
    this->ui->de_from->setDate(a);
    this->currentPeriod=a;
    a.setYMD(QDate::currentDate().year(),QDate::currentDate().month(),
             QDate::currentDate().daysInMonth());
    this->ui->de_to->setDate(a);
    this->InitTable();
    this->toContinue=true;
    this->isChanged=false;
    this->createRecent();

    // connects
    this->ui->twg_table->installEventFilter(this);
    connect(this->ui->tw_central,SIGNAL(currentChanged(int)),this,SLOT(slotChagedTab(int)));
    connect(this->ui->de_from,SIGNAL(dateChanged(QDate)),this,SLOT(slotDateCanged()));
    connect(this->ui->actionAdd_person,SIGNAL(triggered()),this,SLOT(slotActAddPerson()));
    this->slotChagedTab(TAB_HEAD);
    //benya
    connect(this->ui->actionDelete_person,SIGNAL(triggered()),this,SLOT(slotDelPerson()));
    connect(this->ui->actionEdit_person,SIGNAL(triggered()),this,SLOT(slotEditPerson()));
    //Semyon: add edit person by doubleclick and enter
    //connect(this->ui->twg_table, SIGNAL(itemActivated(QTableWidgetItem*)), this, SLOT(slotEditPerson()));
    this->ui->twg_table->installEventFilter(this);
    //Help Menu
    connect(this->ui->actionAbout_Qt,SIGNAL(triggered()),this,SLOT(slotAboutQt()));
    connect(this->ui->action_About_T_13,SIGNAL(triggered()),this,SLOT(slotAboutT13()));
    connect(this->ui->action_Help,SIGNAL(triggered()),this,SLOT(slotAboutT13()));
    //save and save as
    connect(this->ui->action_Save,SIGNAL(triggered()),this,SLOT(slotSave()));
    connect(this->ui->actionSave_as,SIGNAL(triggered()),this,SLOT(slotSaveAs()));
    //open file dialog & open recent
    connect(this->ui->action_Open,SIGNAL(triggered()),this,SLOT(slotOpen()));
    connect(this->ui->actionSe_tting,SIGNAL(triggered()),this,SLOT(slotShowSettings()));
    //new
    connect(this->ui->action_New,SIGNAL(triggered()),this,SLOT(slotNew()));
}

MainWindow::~MainWindow()
{

    delete ui;
}

void MainWindow::slotChagedTab(int i){
    if( i == TAB_TABLE){
        this->ui->actionAdd_person->setEnabled(true);
        this->ui->actionEdit_person->setEnabled(true);
        this->ui->actionDelete_person->setEnabled(true);

    }else{

        this->ui->actionAdd_person->setEnabled(false);
        this->ui->actionEdit_person->setEnabled(false);
        this->ui->actionDelete_person->setEnabled(false);
    }

}

void MainWindow::slotDateCanged(){
    //
    QDate a;
    QDate b = this->ui->de_from->date();
    if(b.month() != this->currentPeriod.month() or b.year() != this->currentPeriod.year()){
        this->currentPeriod = b;
    }

    a.setYMD(this->ui->de_from->date().year() ,this->ui->de_from->date().month(),1);
    this->ui->de_from->setDate(a);

    a.setYMD(this->ui->de_from->date().year(),this->ui->de_from->date().month(),
             this->ui->de_from->date().daysInMonth());
    this->ui->de_to->setDate(a);
}


void MainWindow::InitTable(){
    int count = 3;
    this->ui->twg_table->setColumnCount(count);
    QTableWidgetItem * item = new QTableWidgetItem(tr("FIO"));
    this->ui->twg_table->setHorizontalHeaderItem(0,item);
    item = new QTableWidgetItem(tr("Profession"));
    this->ui->twg_table->setHorizontalHeaderItem(1,item);
    item = new QTableWidgetItem(tr("Table number"));
    this->ui->twg_table->setHorizontalHeaderItem(2,item);
    this->ui->twg_table->horizontalHeader()->setStretchLastSection(true);
    this->ChangeColumnWidth();
}


bool MainWindow::eventFilter(QObject * obj, QEvent *event){
    if(event->type() == QEvent::ContextMenu and obj->objectName() == "twg_table"){
        QMenu menu(this);
        menu.addAction(this->ui->actionAdd_person);
        menu.addAction(this->ui->actionEdit_person);
        menu.addAction(this->ui->actionDelete_person);
        menu.exec(QCursor::pos());
        return true;
    }
    if(event->type() == QEvent::KeyPress and obj->objectName() == "twg_table"){
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
                 if(keyEvent->key() == Qt::Key_Enter or keyEvent->key() == Qt::Key_Return){
                    this->slotEditPerson();
                 }
                 return true;
    }
    if(event->type() == QEvent::Resize and obj->objectName() == "twg_table"){
        this->ChangeColumnWidth();
        return true;
    }
    else{
        return QObject::eventFilter(obj,event);
    }

}

void MainWindow::slotActAddPerson(){
    //this->ui->twg_table->insertRow(this->ui->twg_table->rowCount());

    DiaAddPerson dia(this);

    dia.InitCalendar(this->ui->de_from->date());
    if(dia.exec() == QDialog::Accepted){


        QDomElement empl = this->xmlDoc->createElement("Employee");

        empl.setAttribute("fio",dia.getFio());
        empl.setAttribute("profesio",dia.getProfesio());
        empl.setAttribute("tablenumber",dia.getTableNumber());
        //this->xmlDoc->appendChild(empl);
        QDomNode root = this->xmlDoc->firstChildElement("tabel");
        if(root.isNull())
            qDebug()<<"AAAAAAAAAAAAAAAAAAAAAA";
        else{
            root.appendChild(empl);
            QStringList list = dia.getCalendar();
            for(int i = 0 ; i < list.size() ; i++){
                QDomElement day = this->xmlDoc->createElement("day");
                day.setAttribute("number",QString::number(i+1));
                if(!list.at(i).isEmpty()){
                    day.setAttribute("type",list.at(i).split(",").at(0));
                    day.setAttribute("time",list.at(i).split(",").at(1));
                }
                else{
                    day.setAttribute("type","");
                    day.setAttribute("time","");
                }
                empl.appendChild(day);
            }
        }

        qDebug()<<this->xmlDoc->toString();


        this->ui->twg_table->insertRow(this->ui->twg_table->rowCount());
        qDebug()<<"---"<<this->ui->twg_table->rowCount();
        QTableWidgetItem * it = new QTableWidgetItem(dia.getFio());
        this->ui->twg_table->setItem(this->ui->twg_table->rowCount()-1,0,it);
        it = new QTableWidgetItem(dia.getProfesio());
        this->ui->twg_table->setItem(this->ui->twg_table->rowCount()-1,1,it);
        it = new QTableWidgetItem(dia.getTableNumber());
        this->ui->twg_table->setItem(this->ui->twg_table->rowCount()-1,2,it);


        QList<QString> a;
        for(int i = 0 ; i < this->ui->twg_table->rowCount(); i++){
            a.append(this->ui->twg_table->item(i,0)->text());
        }

        for( int i = 0; i < a.size() ; i++){
            qDebug()<<"FIO N"<<i<<" = "<<a.at(i);
        }
        this->isChanged=true;


    }else{
        qDebug()<<"REJECTED";
    }

}

//benya
void MainWindow::slotDelPerson(){

//Semyon
    if(QMessageBox::question(this,tr("Delete?"),tr("A you sure delete this person?"),
                             QMessageBox::Ok,QMessageBox::Cancel) == QMessageBox::Ok){
        QString fio = this->ui->twg_table->item(this->ui->twg_table->currentRow(),0)->text();
        QString profesio = this->ui->twg_table->item(this->ui->twg_table->currentRow(),1)->text();
        QString tablenumber = this->ui->twg_table->item(this->ui->twg_table->currentRow(),2)->text();
        for(int i=0; i<this->ui->twg_table->columnCount();i++){
            QTableWidgetItem * a = this->ui->twg_table->item(
                    this->ui->twg_table->currentRow(),i);
            if(a!=NULL)
                delete a;
        }
    qDebug()<<"doc_do"<<this->xmlDoc->toString();
    QDomElement tabel = this->xmlDoc->firstChildElement("tabel");
    if(!tabel.isNull()){
            QDomElement element = tabel.firstChildElement("Employee");
            while(!element.isNull()){
                qDebug()<<"isnull "<< element.isNull() << "fio " << element.attribute("fio","qqq");

                if(fio == element.attribute("fio","")
                   and tablenumber  == element.attribute("tablenumber","")
                   and profesio == element.attribute("profesio","")){
                   tabel.removeChild(element);
                }
                element = element.nextSiblingElement("Employee");
           }
    }
    qDebug()<<"doc_posle"<<this->xmlDoc->toString();
    this->ui->twg_table->removeRow(this->ui->twg_table->currentRow());
    this->isChanged=true;
    }
}

void MainWindow::slotExit(){
    emit this->close();
}


void MainWindow::closeEvent(QCloseEvent *event){
    // Проверяем были ли сделаны изменения, если да, то выводим Warning Dialog
    this->QMBisChanged();

    // Проверяем надо ли продолжать выход
    if(toContinue == true){
        this->writeSettings();
        event->accept();
    }
    else{
        event->ignore();
    }
 }


void MainWindow::slotEditPerson(){
    DiaAddPerson dialog(this);
    int cr = this->ui->twg_table->currentRow();
    if(this->ui->twg_table->rowCount()>0){
    dialog.insertFio(this->ui->twg_table->item(cr,0)->text());
    dialog.insertProfesio(this->ui->twg_table->item(cr,1)->text());
    dialog.insertTableNumber(this->ui->twg_table->item(cr,2)->text());
    dialog.InitCalendar(this->ui->de_from->date());
    QStringList strlist;
    QString fio = dialog.getFio();
    QString tablenumber = dialog.getTableNumber();
    QString profesio = dialog.getProfesio();
    QDomElement tabel = this->xmlDoc->firstChildElement("tabel");
    if(!tabel.isNull()){
            QDomElement element = tabel.firstChildElement("Employee");
            while(!element.isNull()){
                qDebug()<<"isnull "<< element.isNull() << "fio " << element.attribute("fio","qqq");
                if(fio == element.attribute("fio","")
                   and tablenumber  == element.attribute("tablenumber","")
                   and profesio == element.attribute("profesio","")){
                    for(int i=0;i<element.childNodes().size();i++){
                        QString type = element.childNodes().at(i).toElement().attribute("type","");
                        QString time = element.childNodes().at(i).toElement().attribute("time","");
                        QString str;
                        str.append(type);
                        str.append(",");
                        str.append(time);
                        strlist.append(str);
                    }

                }
                element = element.nextSiblingElement("Employee");
            }
    }
    dialog.fromXmlToCalendar(strlist);

    if(dialog.exec() == QDialog::Accepted){
        this->ui->twg_table->item(cr,0)->setText(dialog.getFio());
        this->ui->twg_table->item(cr,1)->setText(dialog.getProfesio());
        this->ui->twg_table->item(cr,2)->setText(dialog.getTableNumber());
        QStringList list = dialog.getCalendar();
        QDomElement tabel = this->xmlDoc->firstChildElement("tabel");
        if(!tabel.isNull()){
            QDomElement element = tabel.firstChildElement("Employee");
            while(!element.isNull()){
                if(fio == element.attribute("fio","")
                   and  tablenumber == element.attribute("tablenumber","")
                   and profesio == element.attribute("profesio","")){
                    for(int i=0;i<element.childNodes().size();i++){
                        if(!list.at(i).isEmpty()){
                            QString type = list.at(i).split(",").at(0);
                            element.childNodes().at(i).toElement().setAttribute("type",type);
                            QString time = list.at(i).split(",").at(1);
                            element.childNodes().at(i).toElement().setAttribute("time",time);
                         }
                    }
                }
                element = element.nextSiblingElement("Employee");
            }
        }
        this->isChanged=true;

    }
    }
}

void MainWindow::slotAboutQt(){
    QApplication::aboutQt();
}

void MainWindow::slotAboutT13(){
        QMessageBox::about(this,tr("About"), tr("Application for create T-13 form."));

}
void MainWindow::slotSave(){
    qDebug()<<"fpath is empty"<<fpath.isEmpty();
    if(fpath.isEmpty()){
        QString ddoc = this->ui->de_doc->date().toString("yyyy.MM.dd");
        QString dep = this->ui->le_dept->text();
        QString fname = dep + "_" + ddoc + "." + QString(FILE_FORMAT);
        QString fpathlocal = QFileDialog::getSaveFileName(this,tr("Save file"),fname,"*.t13");
        if(!fpathlocal.isEmpty())
            this->saveFile(fpathlocal);


    }
    else
        this->saveFile(this->fpath);

}
void MainWindow::slotSaveAs(){
    QString ddoc = this->ui->de_doc->date().toString("yyyy.MM.dd");
    QString dep = this->ui->le_dept->text();
    QString fname = dep + "_" + ddoc + "." + QString(FILE_FORMAT);
    QString fpathlocal = QFileDialog::getSaveFileName(this,tr("Save file"),fname,"*.t13");
    if(!fpathlocal.isEmpty())
        this->saveFile(fpathlocal);


}
void MainWindow::saveFile(QString path){
    QFile sfile(path);
    sfile.open(QIODevice::WriteOnly);
    QByteArray ba = this->xmlDoc->toByteArray();
    sfile.write(ba);
    sfile.close();
    this->fpath = path;
    QString title = QString(WINDOW_TITLE);
    if(this->fpath.length() > 21)
         title = title + " " + this->fpath.left(10) + "..." + this->fpath.right(14);
    else
        title = title + " " + this->fpath;
    this->setWindowTitle(title);
    isChanged = false;
    setRecentToCfg(fpath);
    createRecent();

}

void MainWindow::slotOpen(){
    this->QMBisChanged();
    if (toContinue == true) {
        this->fpath = QFileDialog::getOpenFileName(this,tr("Open Dialog"),"","*."+QString(FILE_FORMAT));
        openFile();
        }
}

void MainWindow::openFile(){
    if(!this->fpath.isEmpty()){
        QFile ofile(this->fpath);
        if(ofile.open(QIODevice::ReadOnly)){
            if(!this->xmlDoc->setContent(&ofile))
                QMessageBox::warning(this,"T-13",tr("Can't open file"),QMessageBox::Ok);
            else{
                this->ReinitMW();
                this->ChangeColumnWidth();
            }
            isChanged = false;
            setRecentToCfg(fpath);
            createRecent();
            ofile.close();
        }
    }
}

void MainWindow::slotIsChanged(){

    isChanged=true;
    qDebug()<<"IsChanged"<<isChanged;
    QString sndrName = QObject::sender()->objectName();
    qDebug()<<"sender name "<< sndrName;
    if(sndrName == "le_org") this->ChangeRekvizite("organization",this->ui->le_org->text());
    if(sndrName == "le_dept") this->ChangeRekvizite("departament",this->ui->le_dept->text());
    if(sndrName == "sb_number") this->ChangeRekvizite("table_number",this->ui->sb_number->text());
    if(sndrName == "de_doc") this->ChangeRekvizite("date_doc",this->ui->de_doc->date().toString("dd.MM.yyyy"));
    if(sndrName == "de_from")this->ChangeRekvizite("date_from",this->ui->de_from->date().toString("dd.MM.yyyy"));
    if(sndrName == "de_to")  this->ChangeRekvizite("date_to",this->ui->de_to->date().toString("dd.MM.yyyy"));
    if(sndrName == "le_decm") this->ChangeRekvizite("decision_maker",this->ui->le_decm->text());
    if(sndrName == "le_depm") this->ChangeRekvizite("departament_manager",this->ui->le_depm->text());
    if(sndrName == "le_hrm") this->ChangeRekvizite("hr_manager",this->ui->le_hrm->text());
}

void MainWindow::QMBisChanged(){
    if(isChanged == true) {
        int n = QMessageBox::warning(this,tr("T-13"),tr("Document is changed. Do you want to save this document?"),
                                       QMessageBox::Yes,QMessageBox::No,QMessageBox::Cancel);
        toContinue=0;
        if (n == QMessageBox::Yes) {
            qDebug()<<"QMessageBox: Yes";
            this->slotSave();
            toContinue=1;
        }
        if (n == QMessageBox::No){
            qDebug()<<"QMessageBox: No";
            toContinue=1;
        }
        if (n == QMessageBox::Cancel){
            qDebug()<<"QMessageBox: Cancel";
            toContinue=0;
        }
    }else{
        toContinue=1;
    }

}

void MainWindow::slotPrint(){


    // вызываем диалог с текстом из шаблона
    QWebView wv;
    wv.setHtml(this->createDocument());

          QPrinter printer;
          QPrintPreviewDialog * prevDlg = new QPrintPreviewDialog(&printer);
          connect(prevDlg, SIGNAL(paintRequested(QPrinter*)),
                  &wv, SLOT(print(QPrinter*)));
          prevDlg->exec();
          delete prevDlg;
}

void MainWindow::slotExport(){
    //  основная задача эскпорт в файл html
    QFileDialog diaf;
    // показываем диалог сохранения файла
    QString dfile = diaf.getSaveFileName(this,tr("Save file"),QApplication::applicationDirPath(),tr("html files (*.html)"));
    QFile f;
    f.setFileName(dfile);
    f.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&f);
        out << this->createDocument();

}

QString MainWindow::createDocument(){
    // а тут мы берем шаблон и на его основе генерируем html документ
    // подготавливаем шаблон
    QFile a;
    a.setFileName(":/files/t-13.html");
    a.open(QIODevice::ReadOnly | QIODevice::Text);
    QString ht = QString::fromUtf8(a.readAll());
    QStringList lht = ht.split("\n");

    QString ret;
    QDomElement tabel = this->xmlDoc->firstChildElement("tabel");
    // извлекаем из шаблона первую голову - read from template first head
    int startFH = 0;
    int stopFH = 0;
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$START_FIRST_HEAD$-->",Qt::CaseSensitive)){
            startFH=i;
        }
    }
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$STOP_FIRST_HEAD$-->",Qt::CaseSensitive)){
            stopFH=i;
        }

    }

    for(int i = startFH+1; i < stopFH; i++){
        ret.append(lht.at(i)+"\n");
    }


    // вынимаем из шаблона фрагмент для сотрудника
    int startEmp=0;
    int stopEmp=0;
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$START_EMPL$-->",Qt::CaseSensitive)){
            startEmp=i;
        }
    }
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$STOP_EMPL$-->",Qt::CaseSensitive)){
            stopEmp=i;
        }

    }

    QString EmplTable;
    for(int i = startEmp+1; i < stopEmp; i++){
        EmplTable.append(lht.at(i)+"\n");
    }
    //ret.append(EmplTable);

    // здесь цикл обхода всех сотрудников и математика для обработки данных, с последующей записью в документ
    QStringList emplData;
    for(int i = 0 ; i < tabel.childNodes().size(); i++){
        if(tabel.childNodes().at(i).toElement().tagName() == "Employee"){
            QDomElement empl = tabel.childNodes().at(i).toElement();
            QString tmpStr=EmplTable;
            tmpStr.replace("$FIO_PROFF$",empl.attribute("fio","")+"<br>"+empl.attribute("profesio",""));
            tmpStr.replace("$P_NUM$",QString::number(i));
            tmpStr.replace("$T_NUM$",empl.attribute("tablenumber",""));

            // вынимаем дни
            QStringList days;
            QDomNodeList dlist =  empl.childNodes();
            for(int j = 0 ; j < dlist.size(); j++){
                QString dayNumber = dlist.at(j).toElement().attribute("number","");
                QString datType = dlist.at(j).toElement().attribute("type","");
                QString dayTime = dlist.at(j).toElement().attribute("time","");
            }

            // время за первую и второую половину месяца
            int min_mm=0,min_mh=0,min_tm=0;
            for(int i = 1 ; i <= 31; i++){
                QString tt = dlist.at(i-1).toElement().attribute("time","");
                int min = QTime::fromString(tt,"hh:mm").hour()*60;
                min+=QTime::fromString(tt,"hh:mm").minute();
                if(i<=15){
                    min_mm += min;
                }else{
                    min_mh += min;
                }

                tmpStr.replace("$C"+QString::number(i)+"$",dlist.at(i-1).toElement().attribute("type",""));
                tmpStr.replace("$T"+QString::number(i)+"$",tt);
            }
            tmpStr.replace("$T_MM$",QString::number(min_mm/60)+":"+QString::number(min_mm%60));
            tmpStr.replace("$T_MH$",QString::number(min_mh/60)+":"+QString::number(min_mh%60));
            min_tm = min_mm+min_mh;
            tmpStr.replace("$T_TM$",QString::number(min_tm/60)+":"+QString::number(min_tm%60));

            emplData.append(tmpStr+"\n");
        }

    }


    // вынимаем фрагмент из шаблона  - подвал
    int startFoot=0;
    int stopFoot=0;
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$START_FOOT$-->",Qt::CaseSensitive)){
            startFoot=i;
        }
    }
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$STOP_FOOT$-->",Qt::CaseSensitive)){
            stopFoot=i;
        }

    }
    QString foot;
    for(int i = startFoot+1; i < stopFoot; i++){
        foot.append(lht.at(i)+"\n");
    }

    //ret.append(foot);

    // вынимаем фрагмент второй головы
    int startSH = 0;
    int stopSH = 0;
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$START_SECOND_HEAD$-->",Qt::CaseSensitive)){
            startSH=i;
        }
    }
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$STOP_SECOND_HEAD$-->",Qt::CaseSensitive)){
            stopSH=i;
        }

    }
    QString secondHead;
    for(int i = startSH+1; i < stopSH; i++){
        secondHead.append(lht.at(i)+"\n");
    }


    // вымученный алгоритм заполнения страниц
    int countF=this->cfg->value("rec1",1).toInt();
    int countS=this->cfg->value("rec2",1).toInt();
    qDebug()<<"AA"<<countF<<countS;
    bool isP=true;
    for(int i = 1 ; i <= emplData.size(); i++){
        qDebug()<<"DD"<<(i-countF)%countS;
        qDebug()<<"DATA "<<i;
        ret.append(emplData.at(i-1));
        if(i==countF){
            // вставляем разрыв
            qDebug()<<"R1-------------";
            // всталяем подвал
            ret.append(foot);
            //вставляем новую голову
            ret.append(secondHead);
        }else{
            if((i-countF)%countS == 0){
                // вставляем разрыв два
                qDebug()<<"R2--------------";
                // всталяем подвал
                ret.append(foot);
                //вставляем новую голову
                ret.append(secondHead);
            }else{
            if(i == emplData.size()){
                // последний элемент
                qDebug()<<"R3+++++++++++++++++";
                // всталяем подвал
                ret.append(foot);
            }
            }
        }

    }

    // вынимаем финальные строки из шаблона
    int startEnd=0;
    int stopEnd=0;
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$START_END$-->",Qt::CaseSensitive)){
            startEnd=i;
        }
    }
    for(int i = 0 ; i < lht.size() ; i++){
        if(lht.at(i).contains("<!--$STOP_END$-->",Qt::CaseSensitive)){
            stopEnd=i;
        }

    }
    QString endhtml;
    for(int i = startEnd+1; i < stopEnd; i++){
        endhtml.append(lht.at(i)+"\n");
    }
    ret.append(endhtml);



    // заменяем якора


    if(!tabel.isNull()){
    for(int i = 0 ; i < tabel.childNodes().size(); i++){
        if(tabel.childNodes().at(i).toElement().tagName() == "essential_elements"){
            for(int j = 0 ; j < tabel.childNodes().at(i).childNodes().size(); j++){
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "organization"){
                    ret.replace("$ORGANIZATION$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "departament"){
                    ret.replace("$DEPARTMENT$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "table_number"){
                    ret.replace("$DOC_NUMBER$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "date_doc"){
                    ret.replace("$DOC_DATE$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "date_from"){
                    ret.replace("$FROM$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "date_to"){
                    ret.replace("$TO$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "decision_maker"){
                    ret.replace("$DM1$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "departament_manager"){
                    ret.replace("$DM2$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
                if(tabel.childNodes().at(i).childNodes().at(j).toElement().tagName() == "hr_manager"){
                    ret.replace("$DM3$",tabel.childNodes().at(i).childNodes().at(j).toElement().text());
                }
            }
        }

    }
    }





    // возвращяем многострадальный хытмыл
    return ret;
}

void MainWindow::readSettings(){
    int wx = this->cfg->value("wx",120).toInt();
    int wy = this->cfg->value("wy",120).toInt();
    int ww = this->cfg->value("ww",700).toInt();
    int wh = this->cfg->value("wh",500).toInt();
    this->setGeometry(wx,wy,ww,wh);

    if(this->cfg->value("wx").isNull() || this->cfg->value("wy").isNull()) {
        // Move window to center of screen
        QRect rect = frameGeometry();
        rect.moveCenter(QDesktopWidget().availableGeometry().center());
        move(rect.topLeft());
    }

    // подключаем локализацию
    QTranslator * transmain = new QTranslator();
    if(transmain->load(QString(":/lang/%1.qm").arg(this->cfg->value("lang","ru").toString()))){
        QCoreApplication::installTranslator(transmain);
    }
    this->ui->retranslateUi(this);

}

void MainWindow::writeSettings(){
    QRect rr = this->geometry();
    this->cfg->setValue("wx",rr.x());
    this->cfg->setValue("wy",rr.y());
    this->cfg->setValue("ww",rr.width());
    this->cfg->setValue("wh",rr.height());
}

void MainWindow::slotShowSettings(){
    bool as = this->cfg->value("Autosave",1).toBool();
    int rs = this->cfg->value("RecentSize",RECENT_SIZE).toInt();
    qDebug()<<as<<rs;

    DiaSettings dia(this);
    dia.setAutoSave(as);
    dia.setRecentSize(rs);
    dia.setCountRec1(this->cfg->value("rec1","1").toInt());
    dia.setCountRec2(this->cfg->value("rec2","2").toInt());
    if(dia.exec() == QDialog::Accepted){
        bool a = dia.getAutoSave();
        int r = dia.getRecentSize();
        qDebug()<<"Autosave ="<<a;
        qDebug()<<"RecentCount ="<<r;
        //this->cfg->setValue("wx",rr.x());
        this->cfg->setValue("Autosave",a);
        this->cfg->setValue("RecentSize",r);
        this->cfg->setValue("rec1",dia.getCountRec1());
        this->cfg->setValue("rec2",dia.getCountRec2());
        this->createRecent();
    }
    else{}
   }


void MainWindow::initXml(){
    this->xmlDoc = new QDomDocument("new");
    QDomElement tabel = this->xmlDoc->createElement("tabel");
    this->xmlDoc->appendChild(tabel);
    QDomElement essent_elem = this->xmlDoc->createElement("essential_elements");
    tabel.appendChild(essent_elem);
    QDomElement organization = this->xmlDoc->createElement("organization");
    QDomText orgname = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(organization);
    organization.appendChild(orgname);
    QDomElement dep = this->xmlDoc->createElement("departament");
    QDomText depname = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(dep);
    dep.appendChild(depname);
    QDomElement tbnum = this->xmlDoc->createElement("table_number");
    QDomText tbnumval = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(tbnum);
    tbnum.appendChild(tbnumval);
    QDomElement datedoc = this->xmlDoc->createElement("date_doc");
    QDomText dateval = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(datedoc);
    datedoc.appendChild(dateval);
    QDomElement datefrom = this->xmlDoc->createElement("date_from");
    QDomText datefromval = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(datefrom);
    datefrom.appendChild(datefromval);
    QDomElement dateto = this->xmlDoc->createElement("date_to");
    QDomText datetoval = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(dateto);
    dateto.appendChild(datetoval);
    QDomElement decmkr = this->xmlDoc->createElement("decision_maker");
    QDomText decmkrval = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(decmkr);
    decmkr.appendChild(decmkrval);
    QDomElement depmngr = this->xmlDoc->createElement("departament_manager");
    QDomText depmngrval = this->xmlDoc->createTextNode("");
    essent_elem.appendChild(depmngr);
    depmngr.appendChild(depmngrval);
    QDomElement hr = this->xmlDoc->createElement("hr_manager");
    QDomText hrval= this->xmlDoc->createTextNode("");
    essent_elem.appendChild(hr);
    hr.appendChild(hrval);

}
//функция меняет значение xml тега , входные параметры имя тега и значение
void MainWindow::ChangeRekvizite(QString rekname, QString rekvalue){
    QDomElement tabel = this->xmlDoc->firstChildElement("tabel");
    if(!tabel.isNull()){
        QDomElement rekvzts = tabel.firstChildElement("essential_elements");
        if(!rekvzts.isNull()){
            QDomElement rek = rekvzts.firstChildElement(rekname);
            if(rek.childNodes().size() == 1){
                rek.childNodes().at(0).setNodeValue(rekvalue);
            }
            else QMessageBox::warning(this,"T-13",tr("wrong xml"),QMessageBox::Ok);
        }
        else QMessageBox::warning(this,"T-13",tr("wrong xml"),QMessageBox::Ok);
    }
    else QMessageBox::warning(this,"T-13",tr("wrong xml"),QMessageBox::Ok);

}
//функция перезаполняет данные из xml
void MainWindow::ReinitMW(){
    QDomElement tabel = this->xmlDoc->firstChildElement("tabel");
    if(!tabel.isNull()){
        QDomElement rekvzts = tabel.firstChildElement("essential_elements");
        if(!rekvzts.isNull()){
            QDomElement org = rekvzts.firstChildElement("organization");
                if(!org.isNull()){
                    this->ui->le_org->setText(org.text());
                }
            QDomElement dep = rekvzts.firstChildElement("departament");
                 if(!dep.isNull()){
                    this->ui->le_dept->setText(dep.text());
                 }
            QDomElement tblnum = rekvzts.firstChildElement("table_number");
                  if(!tblnum.isNull()){
                     this->ui->sb_number->setValue(tblnum.text().toInt());
                  }
            QDomElement ddoc = rekvzts.firstChildElement("date_doc");
                  if(!ddoc.isNull()){
                    this->ui->de_doc->setDate(QDate::fromString(ddoc.text(),"dd.MM.yyyy"));
                  }
            QDomElement dfrom = rekvzts.firstChildElement("date_from");
                  if(!dfrom.isNull()){
                     this->ui->de_from->setDate(QDate::fromString(dfrom.text(),"dd.MM.yyyy"));
                  }
           // QDomElement dto = rekvzts.firstChildElement("date_to");
             //      if(!dto.isNull()){
               //       this->ui->de_to->setDate(QDate::fromString(dto.text(),"dd.MM.yyyy"));
                 //  }
            QDomElement decmaker = rekvzts.firstChildElement("decision_maker");
                  if(!decmaker.isNull()){
                      this->ui->le_decm->setText(decmaker.text());
                  }
            QDomElement depman = rekvzts.firstChildElement("departament_manager");
                  if(!depman.isNull()){
                       this->ui->le_depm->setText(depman.text());
                  }
            QDomElement hrman = rekvzts.firstChildElement("hr_manager");
                  if(!hrman.isNull()){
                            this->ui->le_hrm->setText(hrman.text());
                        }
            //удаляем содержимое табличной части
            int rc = this->ui->twg_table->rowCount();
            if(rc > 0){
                for(int k = rc-1; k >= 0; k--){
                    for(int j = 0; j < this->ui->twg_table->columnCount(); j++){
                        QTableWidgetItem * item = this->ui->twg_table->item(k,j);
                        if(item != NULL){
                            delete item;
                        }
                    }
                    this->ui->twg_table->removeRow(k);
                }
            }
            //заполняем табличную часть значениями из файла
            if(tabel.childNodes().size()>1){
                for(int i = 1;i < tabel.childNodes().size();i++){
                    QDomElement empl = tabel.childNodes().at(i).toElement();
                    this->ui->twg_table->insertRow(this->ui->twg_table->rowCount());
                    QTableWidgetItem  * item = new QTableWidgetItem(empl.attribute("fio",""));
                    this->ui->twg_table->setItem(this->ui->twg_table->rowCount()-1,0,item);
                    item = new QTableWidgetItem(empl.attribute("profesio",""));
                    this->ui->twg_table->setItem(this->ui->twg_table->rowCount()-1,1,item);
                    item = new QTableWidgetItem(empl.attribute("tablenumber",""));
                    this->ui->twg_table->setItem(this->ui->twg_table->rowCount()-1,2,item);
                    this->ui->twg_table->resizeColumnsToContents();
                    this->ui->twg_table->resizeRowsToContents();
                }

            }
        }

     }
}
//изменяет ширину столбцов(равномерно)
void MainWindow::ChangeColumnWidth(){
    //вычисляем ширину столбца, число 10 необходимо для того чтобы
//    не появлялась полоса прокрутки(число подобрано эмпирически)
    int colw = this->ui->twg_table->width()/this->ui->twg_table->columnCount()-10;
    qDebug()<<"colw "<<colw <<"table width"<< this->ui->twg_table->width();
    for(int i = 0; i < this->ui->twg_table->columnCount(); i++){
        this->ui->twg_table->setColumnWidth(i,colw);
    }
}

void MainWindow::slotNew(){
    this->QMBisChanged();
    if(this->toContinue == true){
        this->initXml();
        this->ReinitMW();
        this->isChanged=false;
    }
}

void MainWindow::createRecent(){
    //If menu already enabled, reinit recent menu.
    if(this->ui->menuRecently_Opened_Files->isEnabled()){
            this->ui->menuRecently_Opened_Files->clear();
    }
    QStringList files = this->cfg->value("Recent").toStringList();
    // If recent list is not empty create recent menu
    if(files.value(0) != ""){
        //Enable Recent Menu
        this->ui->menuRecently_Opened_Files->setEnabled(1);

        // Recent list
        int RecentSize = this->cfg->value("RecentSize",RECENT_SIZE).toInt();

        qDebug()<<"List size:"<<files.size();
        for(int i=0;i<RecentSize;i++){
            if(files.value(i) != ""){
                qDebug()<<"i ="<<i<<"="<<files.value(i);
                // If element is not empty, now create action for this element
                QAction *recentAct = new QAction(files.value(i),this);
                // Создаем вектор указателей на элементы меню для очистки в памяти в дальнейшем
                this->vec.append(recentAct);
                // Create menu item and connect
                connect(recentAct, SIGNAL(triggered()),this,SLOT(slotOpenRecentFile()));
                this->ui->menuRecently_Opened_Files->addAction(recentAct);
            }
        }
        // Add separator
        this->ui->menuRecently_Opened_Files->addSeparator();

        // Create clear history item
        clearAct = new QAction(tr("&Clear History"), this);
        connect(clearAct, SIGNAL(triggered()), this, SLOT(slotClearRecent()));
        this->ui->menuRecently_Opened_Files->addAction(clearAct);
        }else{
        qDebug()<<"Recent list is Empty!";
        }
}

void MainWindow::setRecentToCfg(QString filename){
    int MaxRecentFiles = this->cfg->value("RecentSize",RECENT_SIZE).toInt();
    QStringList files = this->cfg->value("Recent").toStringList();
    files.removeAll(filename);
    files.prepend(filename);
    while(files.size() > MaxRecentFiles){
        files.removeLast();
    }
    this->cfg->setValue("Recent",files);
}

void MainWindow::slotClearRecent(){
    QString list;
    this->cfg->setValue("Recent",list);
    this->ui->menuRecently_Opened_Files->setDisabled(1);
    this->ui->menuRecently_Opened_Files->clear();

    // Удаляем элементы из памяти (чтобы не было Memory Licks)
    for(int i = 0; i < this->vec.size(); i++){
        delete this->vec.at(i);
    }
    vec.clear();
    createRecent();
}

void MainWindow::slotOpenRecentFile(){
    if(isChanged){
        this->QMBisChanged();
    }
    if (toContinue == true) {
        QAction *a = qobject_cast<QAction*>(sender());
        qDebug()<<"Recent sender filename:"<<a->text();
        this->fpath = a->text();
        openFile();
    }
}
